package com.loongtech.bi.action.bigame;

import com.loongtech.bi.action.BaseBiSearchAction;
import com.loongtech.bi.manager.game.ActivityGameManager;
import com.loongtech.bi.manager.system.GameParamConfigManager;
import com.loongtech.bi.support.CommonGameParam;
import com.loongtech.bi.support.chart.ChartTool;
import com.loongtech.bi.support.chart.ChartType;
import com.loongtech.bi.support.chart.ChartUIData;
import com.loongtech.core.util.Time;
import com.loongtech.core.util.Utils;
import org.datanucleus.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 游戏内分析-等级分析Action
 * @author Marin
 * @date 2015年09月17日
 */
@Controller
@Scope("session")
@RequestMapping("/game/activityGame")
public class ActivityGameBiAction extends BaseBiSearchAction {
	private static final long serialVersionUID = 1L;
    private String dateRadio = "7";  // 切换的天数：7=近7天。15=近15天。30=近30天，0=自选时间
    private Date dateStart = new Date(Time.getBeginningOfDay(Time.currentTime() - 7 * Time.DAY));  // 自选时间：开始时间
    private Date dateEnd = new Date(Time.getBeginningOfDay(Time.currentTime() - Time.DAY));  // 自选时间：结束时间

    private String queryUserType = GameParamConfigManager.ALL_FLAT;  // 选中的用户类型
    private Map<String, String> userTypes = GameParamConfigManager.getItems(CommonGameParam.VIP_USER_TYPE);  // 用户类型：大V，小V，免费。根据viplevel划分
    private Map<String, String> userTypesRevise = GameParamConfigManager.getItemsRevise(CommonGameParam.VIP_USER_TYPE);

    private Map<String, String> ats = GameParamConfigManager.getItemsRevise(CommonGameParam.ACTIVITY_TYPE);  // 活动类型：活动ID=类型ID
    private Map<String, List<String>> typeActivitys;  // 活动类型包含的活动ID：类型ID=List(1,2,3)

    private String activityType;  // 参与率选中的活动类型
    private String activityType2;  // 人均参与次数选中的活动类型
    private Map<String, String> activityTypes;  // 可选的活动类型列表

    private List<String> selectedActivities;  // 参与率选中的活动列表
    private List<String> selectedActivities2;  // 人均参与次数选中的活动列表
    private Map<String, String> activityItmes;  // 可选的活动

    private ChartUIData activityChart;  // 参与率chart
    private List<ActivityGameManager.ActivityUserJoinRateData> activityDatas;  // 参与率数据

    private ChartUIData activityChart2;  // 人均参与次数chart
    private List<ActivityGameManager.ActivityUserJoinNumData> activityDatas2;  // 参与率数据

    private List<Integer> queryVipLevels;

    @Autowired
	private ActivityGameManager activityGameManager;

    @RequestMapping(value = "initParam.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void initParam(HttpServletRequest request, HttpServletResponse response, String callback) {
        Map<String, Object> result = new HashMap<>();
        try {
            activityItmes = new LinkedHashMap<>();
            selectedActivities = new ArrayList<>();
            selectedActivities2 = new ArrayList<>();

            for (Map.Entry<String, String> entry : GameParamConfigManager.getItems(CommonGameParam.ACTIVITY_NAME).entrySet()) {
                if (!GameParamConfigManager.ALL_FLAT.equals(entry.getValue())) {
                    activityItmes.put(entry.getKey(), entry.getValue());

                    if (selectedActivities.size() < 6) {
                        selectedActivities.add(entry.getValue());
                    }

                    if (selectedActivities2.size() < 6) {
                        selectedActivities2.add(entry.getValue());
                    }
                }
            }

            activityTypes = new LinkedHashMap<>();
            typeActivitys = new LinkedHashMap<>();
            int i = 1;
            for (Map.Entry<String, String> entry : ats.entrySet()) {
                String aid = entry.getKey();  // 活动ID
                String tid = entry.getValue();  // 类型ID

                if (GameParamConfigManager.ALL_FLAT.equals(aid)) {
                    continue;
                }

                if (i == 1) {
                    activityType = tid;
                    activityType2 = tid;
                    i++;
                }

                String tname = GameParamConfigManager.getItemsRevise(CommonGameParam.ACTIVITY_TYPE_NAME).get(tid);
                activityTypes.put(tname == null ? tid : tname, tid);

                List<String> ll = typeActivitys.get(tid);
                if (ll == null) {
                    ll = new ArrayList<>();
                    typeActivitys.put(tid, ll);
                }
                ll.add(aid);
            }

            result.put("res", "0");
            result.put("serverItmes", serverItmes);
            result.put("channelItmes", channelItmes);
            result.put("platformItmes", platformItmes);

            result.put("userTypes", userTypes);
            result.put("activityTypes", activityTypes);
            result.put("activityItmes", activityItmes);
            result.put("selectedActivities", selectedActivities);
            result.put("selectedActivities2", selectedActivities2);

            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
            return;
        }
    }

    @RequestMapping(value = "search.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void search(HttpServletRequest request, HttpServletResponse response, @RequestParam String dstart, @RequestParam String dend, @RequestParam String platform, @RequestParam String channel, @RequestParam String server, @RequestParam String userType, @RequestParam String activityType, @RequestParam List<String> activities, @RequestParam String activityType2, @RequestParam List<String> activities2, String callback) {
        Map<String, Object> result = new HashMap<>();
        try {
            dateStart = Time.formatDate(dstart, Time.TIMEPATTERN_SIMPLE);
            dateEnd = Time.formatDate(dend, Time.TIMEPATTERN_SIMPLE);
            queryPlatform = platform;
            queryChannel = channel;
            queryServer = server;
            queryUserType = userType;
            this.activityType = activityType;
            selectedActivities = Utils.getStringList(activities);
            this.activityType2 = activityType2;
            selectedActivities2 = Utils.getStringList(activities2);

            queryVipLevels = new ArrayList<>();
            if (!GameParamConfigManager.ALL_FLAT.equals(queryUserType)) {
                String ss = userTypesRevise.get(queryUserType);
                if (!StringUtils.isEmpty(ss)) {
                    if (ss.contains("[") && ss.contains("]")) {
                        String s = ss.split("\\[")[1].split("]")[0];

                        if (s.contains("-")) {
                            String[] sa = s.split("-");

                            int start = Integer.parseInt(sa[0]);
                            int end = Integer.parseInt(sa[1]);
                            for (int i = start; i <= end; i++) {
                                queryVipLevels.add(i);
                            }
                        } else {
                            queryVipLevels.add(Integer.parseInt(s));
                        }
                    } else {
                        result.put("res", "1");
                        result.put("msg", "用户类型配置不正确，正确格式为: 小V[2-9]  大V[0]  !");
                        printToJson(response, result, callback);

                        return;
                    }
                }
            }

            activityDatas = activityGameManager.getRoleAcitvityJoinRateDatas(dateStart, dateEnd, queryPlatform, queryChannel, queryServer, queryVipLevels, activityType, selectedActivities);
            if (activityDatas != null && activityDatas.size() > 0) {
                activityChart = new ChartUIData();
                activityChart.setJsonStr(new ChartTool(activityDatas, ActivityGameManager.ActivityUserJoinRateData.class, "").loadData(activityChart.getJsonType(), true));
            } else {
                activityChart = null;
            }

            activityDatas2 = activityGameManager.getRoleAcitvityJoinNumDatas(dateStart, dateEnd, queryPlatform, queryChannel, queryServer, queryVipLevels, activityType2, selectedActivities2);
            if (activityDatas2 != null && activityDatas2.size() > 0) {
                activityChart2 = new ChartUIData();
                activityChart2.setJsonType(ChartType.COLUMN.type);
                activityChart2.setJsonStr(new ChartTool(activityDatas2, ActivityGameManager.ActivityUserJoinNumData.class, "").loadData(activityChart2.getJsonType(), false));
            } else {
                activityChart2 = null;
            }

            result.put("res", "0");
            result.put("activityDatas", activityDatas);
            result.put("activityChart", activityChart);
            result.put("activityChart2", activityChart2);

            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
        }
	}

    @RequestMapping(value = "updateServer.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void updateServer(HttpServletRequest request, HttpServletResponse response, String server, String callback) {
        try {
            queryServer = server;
            selectedServer();
            Map<String, Object> result = new HashMap<>();
            result.put("res", "0");
            result.put("channelItmes", channelItmes);
            result.put("platformItmes", platformItmes);
            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
            return;
        }
    }

    @RequestMapping(value = "updateChannel.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void updateChannel(HttpServletRequest request, HttpServletResponse response, String channel, String callback) {
        try {
            queryChannel = channel;
            updateServerItmes();
            Map<String, Object> result = new HashMap<>();
            result.put("res", "0");
            result.put("serverItmes", serverItmes);
            result.put("platformItmes", platformItmes);
            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<String, Object>();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
            return;
        }
    }

    @RequestMapping(value = "updatePlatform.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void updatePlatform(HttpServletRequest request, HttpServletResponse response, String platform, String callback) {
        try {
            queryPlatform = platform;
            updateChannelItmes();
            Map<String, Object> result = new HashMap<>();
            result.put("res", "0");
            result.put("serverItmes", serverItmes);
            result.put("channelItmes", channelItmes);
            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
            return;
        }
    }

    @RequestMapping(value = "updateActivityType.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void updateActivityType(HttpServletRequest request, HttpServletResponse response, @RequestParam String dstart, @RequestParam String dend, @RequestParam String platform, @RequestParam String channel, @RequestParam String server, @RequestParam String userType, @RequestParam String activityType, @RequestParam List<String> activities, String callback) {
        Map<String, Object> result = new HashMap<>();
        try {
            dateStart = Time.formatDate(dstart, Time.TIMEPATTERN_SIMPLE);
            dateEnd = Time.formatDate(dend, Time.TIMEPATTERN_SIMPLE);
            queryPlatform = platform;
            queryChannel = channel;
            queryServer = server;
            queryUserType = userType;
            this.activityType = activityType;
            this.selectedActivities = activities;

            queryVipLevels = new ArrayList<>();
            if (!GameParamConfigManager.ALL_FLAT.equals(queryUserType)) {
                String ss = userTypesRevise.get(queryUserType);
                if (!StringUtils.isEmpty(ss)) {
                    if (ss.contains("[") && ss.contains("]")) {
                        String s = ss.split("\\[")[1].split("]")[0];

                        if (s.contains("-")) {
                            String[] sa = s.split("-");

                            int start = Integer.parseInt(sa[0]);
                            int end = Integer.parseInt(sa[1]);
                            for (int i = start; i <= end; i++) {
                                queryVipLevels.add(i);
                            }
                        } else {
                            queryVipLevels.add(Integer.parseInt(s));
                        }
                    } else {
                        result.put("res", "1");
                        result.put("msg", "用户类型配置不正确，正确格式为: 小V[2-9]  大V[0]  !");
                        printToJson(response, result, callback);

                        return;
                    }
                }
            }

            activityDatas = activityGameManager.getRoleAcitvityJoinRateDatas(dateStart, dateEnd, queryPlatform, queryChannel, queryServer, queryVipLevels, activityType, selectedActivities);
            if (activityDatas != null && activityDatas.size() > 0) {
                activityChart = new ChartUIData();
                activityChart.setJsonStr(new ChartTool(activityDatas, ActivityGameManager.ActivityUserJoinRateData.class, "").loadData(activityChart.getJsonType(), true));
            } else {
                activityChart = null;
            }

            result.put("res", "0");
            result.put("activityDatas", activityDatas);
            result.put("chart", activityChart);

            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
        }
    }

    // 人均参与次数切换活动类型
    @RequestMapping(value = "updateActivityType2.do", method = {RequestMethod.GET, RequestMethod.POST})
    public void updateActivityType2(HttpServletRequest request, HttpServletResponse response, @RequestParam String dstart, @RequestParam String dend, @RequestParam String platform, @RequestParam String channel, @RequestParam String server, @RequestParam String userType, @RequestParam String activityType, @RequestParam List<String> activities, String callback) {
        Map<String, Object> result = new HashMap<>();
        try {
            dateStart = Time.formatDate(dstart, Time.TIMEPATTERN_SIMPLE);
            dateEnd = Time.formatDate(dend, Time.TIMEPATTERN_SIMPLE);
            queryPlatform = platform;
            queryChannel = channel;
            queryServer = server;
            queryUserType = userType;
            this.activityType2 = activityType;
            this.selectedActivities2 = activities;

            queryVipLevels = new ArrayList<>();
            if (!GameParamConfigManager.ALL_FLAT.equals(queryUserType)) {
                String ss = userTypesRevise.get(queryUserType);
                if (!StringUtils.isEmpty(ss)) {
                    if (ss.contains("[") && ss.contains("]")) {
                        String s = ss.split("\\[")[1].split("]")[0];

                        if (s.contains("-")) {
                            String[] sa = s.split("-");

                            int start = Integer.parseInt(sa[0]);
                            int end = Integer.parseInt(sa[1]);
                            for (int i = start; i <= end; i++) {
                                queryVipLevels.add(i);
                            }
                        } else {
                            queryVipLevels.add(Integer.parseInt(s));
                        }
                    } else {
                        result.put("res", "1");
                        result.put("msg", "用户类型配置不正确，正确格式为: 小V[2-9]  大V[0]  !");
                        printToJson(response, result, callback);

                        return;
                    }
                }
            }

            activityDatas2 = activityGameManager.getRoleAcitvityJoinNumDatas(dateStart, dateEnd, queryPlatform, queryChannel, queryServer, queryVipLevels, activityType2, selectedActivities2);
            if (activityDatas2 != null && activityDatas2.size() > 0) {
                activityChart2 = new ChartUIData();
                activityChart2.setJsonType(ChartType.COLUMN.type);
                activityChart2.setJsonStr(new ChartTool(activityDatas2, ActivityGameManager.ActivityUserJoinNumData.class, "").loadData(activityChart2.getJsonType(), false));
            } else {
                activityChart2 = null;
            }

            result.put("res", "0");
            result.put("chart", activityChart2);

            printToJson(response, result, callback);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("res", "1");
            result.put("msg", e.getMessage());
            printToJson(response, result, callback);
        }
    }

    @Override
    public void search() {
    }

    @Override
	protected String csvContent() {
		return "活动分布";
	}

	@Override
    protected String csvFileName() {
	    return "活动分布";
    }


    public String getDateRadio() {
        return dateRadio;
    }

    public void setDateRadio(String dateRadio) {
        this.dateRadio = dateRadio;
    }

    @Override
    public Date getDateStart() {
        return dateStart;
    }

    @Override
    public void setDateStart(Date dateStart) {
        this.dateStart = dateStart;
    }

    @Override
    public Date getDateEnd() {
        return dateEnd;
    }

    @Override
    public void setDateEnd(Date dateEnd) {
        this.dateEnd = dateEnd;
    }

    public Map<String, String> getActivityTypes() {
        return activityTypes;
    }

    public void setActivityTypes(Map<String, String> activityTypes) {
        this.activityTypes = activityTypes;
    }

    public String getQueryUserType() {
        return queryUserType;
    }

    public void setQueryUserType(String queryUserType) {
        this.queryUserType = queryUserType;
    }

    public Map<String, String> getUserTypes() {
        return userTypes;
    }

    public void setUserTypes(Map<String, String> userTypes) {
        this.userTypes = userTypes;
    }

    public Map<String, String> getUserTypesRevise() {
        return userTypesRevise;
    }

    public void setUserTypesRevise(Map<String, String> userTypesRevise) {
        this.userTypesRevise = userTypesRevise;
    }

    public String getActivityType() {
        return activityType;
    }

    public void setActivityType(String activityType) {
        this.activityType = activityType;
    }

    public ChartUIData getActivityChart() {
        return activityChart;
    }

    public void setActivityChart(ChartUIData activityChart) {
        this.activityChart = activityChart;
    }

    public List<ActivityGameManager.ActivityUserJoinRateData> getActivityDatas() {
        return activityDatas;
    }

    public void setActivityDatas(List<ActivityGameManager.ActivityUserJoinRateData> activityDatas) {
        this.activityDatas = activityDatas;
    }

    public Map<String, String> getAts() {
        return ats;
    }

    public void setAts(Map<String, String> ats) {
        this.ats = ats;
    }

    public Map<String, List<String>> getTypeActivitys() {
        return typeActivitys;
    }

    public void setTypeActivitys(Map<String, List<String>> typeActivitys) {
        this.typeActivitys = typeActivitys;
    }

    public Map<String, String> getActivityItmes() {
        return activityItmes;
    }

    public void setActivityItmes(Map<String, String> activityItmes) {
        this.activityItmes = activityItmes;
    }

    public List<String> getSelectedActivities() {
        return selectedActivities;
    }

    public void setSelectedActivities(List<String> selectedActivities) {
        this.selectedActivities = selectedActivities;
    }

    public String getActivityType2() {
        return activityType2;
    }

    public void setActivityType2(String activityType2) {
        this.activityType2 = activityType2;
    }

    public List<String> getSelectedActivities2() {
        return selectedActivities2;
    }

    public void setSelectedActivities2(List<String> selectedActivities2) {
        this.selectedActivities2 = selectedActivities2;
    }

    public ChartUIData getActivityChart2() {
        return activityChart2;
    }

    public void setActivityChart2(ChartUIData activityChart2) {
        this.activityChart2 = activityChart2;
    }

    public List<ActivityGameManager.ActivityUserJoinNumData> getActivityDatas2() {
        return activityDatas2;
    }

    public void setActivityDatas2(List<ActivityGameManager.ActivityUserJoinNumData> activityDatas2) {
        this.activityDatas2 = activityDatas2;
    }
}
